#include <algorithm>
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> res;
        for (int i=0; i<nums.size(); i++){
            if(i > 0 && nums[i] == nums[i - 1]) continue;//判断当前遍历值和前一位值是否相等，相等的话说明已经处理过 ，删除

            int left = i + 1;
            int right = nums.size() - 1;
            
            while (right > left){
                if (nums[i] + nums[left] + nums[right] > 0) right--;
                else if (nums[i] + nums[left] + nums[right] < 0) left++;
                else {
                    res.push_back({nums[i], nums[left], nums[right]});
                    while (right > left && nums[left] == nums[left + 1]) left++; // right > left是为了防止数组越界访问
                    while (right > left && nums[right] == nums[right - 1]) right--;
                    left++;
                    right--;
                }
            }
        }
        return res;
    }
};